//
//  GidePage.swift
//  Uber
//
//  Created by ma c on 16/1/30.
//  Copyright © 2016年 ma c. All rights reserved.
//

import UIKit
import AVFoundation

class GidePage: FxBasePage {
    
    @IBOutlet var backImageView:UIImageView?
    @IBOutlet var backView:UIView?
    var player:AVPlayer!
    
    var playItem:AVPlayerItem!
    
    var location:FxLocation!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initPlayVideos()
        doAnimation()
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    func doAnimation(){
    
        var images:[UIImage]=[]
        var image:UIImage?
        var imagename:String?
        for  i in 0...67{
          
            imagename = "logo-" + String(format: "%03d.png", i)
            image = UIImage(named: imagename!)
            images.insert(image!, atIndex: i)
            
        }
        
        backImageView?.animationImages = images
        backImageView?.animationDuration = 5
        backImageView?.animationRepeatCount = 1
        backImageView?.startAnimating()
        
    
    }
    
    func initPlayVideos(){
    
           let path = NSBundle.mainBundle().pathForResource("welcome_video", ofType: "mp4")
            let url = NSURL.fileURLWithPath(path!)
        
            playItem = AVPlayerItem(URL: url)
            player = AVPlayer(playerItem: playItem)
        
            let playerLayer = AVPlayerLayer(player: player)
        
            playerLayer.frame =  backView!.bounds
        
            playerLayer.videoGravity = AVLayerVideoGravityResizeAspect//视频等比例缩放适配
        
        
            backView?.layer.insertSublayer(playerLayer, atIndex: 0)
            backView?.alpha = 0.0
        
         UIView.animateWithDuration(0.7, delay:5, options: .CurveEaseOut, animations: { () -> Void in
                
                self.backView?.alpha = 1.0
                self.player!.play()
                
                }, completion: {finished in
                                print("Animation End")
                    
            })
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didFinishVideo:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playItem)
        
        
        
        
        
        
        
        
    }
    
    //视频循环播放
    func didFinishVideo(sender:NSNotification){
    
        let item = sender.object as! AVPlayerItem
        
        item.seekToTime(kCMTimeZero)
        
        self.player.play()
    
    }
    
    
    @IBAction func doLogin(sender: UIButton) {
        
        location = FxLocation()
        location.startLocation()
        
        

    }
   
   
}
